import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

@RequestMapping("/captcha")
@RestController
public class HuToolCaptchaController {
    @Autowired
    private CaptchaProperties captchaProperties;

    @RequestMapping("/getCaptcha")
    public void getCode(HttpSession session, HttpServletResponse response) {
        LineCaptcha lineCaptcha =
                CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(),
                        captchaProperties.getHeight());
        response.setContentType("image/jpeg");
        response.setHeader("Pragma", "No-cache");
        try {
            lineCaptcha.write(response.getOutputStream());
            session.setAttribute(captchaProperties.getSession().getKey(),
                    lineCaptcha.getCode());
            session.setAttribute(captchaProperties.getSession().getDate(), new
                    Date());
            System.out.println("⽣成的验证码:" + lineCaptcha.getCode());
            response.getOutputStream().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
